package tongwentongshu.com.app.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;


import java.util.Arrays;

import butterknife.BindView;
import butterknife.OnClick;
import tongwentongshu.com.app.App;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.bean.AppItem;
import tongwentongshu.com.app.bean.PersonalBean;
import tongwentongshu.com.app.bean.SignBean;
import tongwentongshu.com.app.contract.CallBackColonyContract;
import tongwentongshu.com.app.contract.PersonalCenterContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.dialog.AlertUtils;
import tongwentongshu.com.app.model.PersonalCenterModel;
import tongwentongshu.com.app.presenter.PersonalCenterPresenter;
import tongwentongshu.com.app.utils.FileUtil;
import tongwentongshu.com.app.utils.GlideUtil;
import tongwentongshu.com.app.utils.ToastUtil;

/**
 * Created by XiongBin on 2017/7/10.
 */

public class PersonalCenterActivity extends BaseActivity implements PersonalCenterContract.View {
    @BindView(R.id.ll_read_people)
    RecyclerView mRecyclerView;
    @BindView(R.id.title_share)
    ImageView setting;//设置
    @BindView(R.id.tv_me_head)
    ImageView userPic;//头像
    @BindView(R.id.tv_user_name)
    TextView userName;//昵称
    @BindView(R.id.tv_shudou)
    TextView shudou;//书豆
    @BindView(R.id.tv_auth)
    TextView auth;//认证
    @BindView(R.id.tv_sign)
    TextView sign;//签到蚊子
    @BindView(R.id.iv_auth)
    ImageView authiv;//认证图标
    @BindView(R.id.iv_user_sex)
    ImageView userSex;//性别
    private PersonalCenterAdapter adapter;
    private PersonalCenterPresenter personalCenterPresenter;
    private PersonalCenterModel personalCenterModel;
    private int mWidth;
    private int mHeight;
    MyHandler myHandler;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_personal_center;
    }

    @Override
    protected int getTitleId() {
        return R.string.personal_center;
    }

    @Override
    protected void initView() {
//        App.getApplication().addMallActivity(this);
        setting.setImageResource(R.drawable.setting);
        setting.setVisibility(View.VISIBLE);
        userPic.post(new Runnable() {
            @Override
            public void run() {
                mWidth = userPic.getWidth();
                mHeight = userPic.getHeight();
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(final BaseQuickAdapter adapter, final View view, final int position) {
                startActivity(classes[position]);
            }
        });
        adapter = new PersonalCenterAdapter();
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        personalCenterPresenter = new PersonalCenterPresenter(this);
        personalCenterModel = new PersonalCenterModel(this);
    }

    Class[] classes = {MyReadingActivity.class, MyShareActivity.class, MyFollowActivity.class, MyCollectionActivity.class, OnlineHelpActivity.class, PoliteInvitationActivity.class, AboutUsActivity.class};
    String[] itemList = {"我的收获", "我的贡献", "以书会友", "我的收藏", "在线帮助", "邀请有礼", "关于我们"};
    int[] pic = {R.drawable.p1, R.drawable.p2, R.drawable.p3, R.drawable.p4, R.drawable.p5, R.drawable.p7, R.drawable.p8,};
    PersonalBean msg;

    @Override
    public void onSuccess(PersonalBean msg) {
        this.msg = msg;
        if (msg.getData().getSex().equals("1")) {
            userSex.setImageResource(R.drawable.mr);
        } else if (msg.getData().getSex().equals("0")) {
            userSex.setImageResource(R.drawable.xx);
        } else {
            userSex.setImageResource(R.drawable.miss);
        }
        userName.setText(msg.getData().getUser_nickname());
        shudou.setText(msg.getData().getDoudou() + "书豆");
        Cache.getUser().setMemo(msg.getData().getSignature());
        GlideUtil.setImage(mContext, msg.getData().getAvatar(), R.drawable.head_img, R.drawable.head_img, userPic);
        initSign();
        initStatus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        personalCenterPresenter.initMyInfo();

    }

    void initStatus() {
        if (msg.getData().getUser_status().equals("2")) {
            auth.setText("去认证");
            authiv.setImageResource(R.drawable.pre_btn_smrz);
        } else if (msg.getData().getMoney().equals("0")) {
            authiv.setImageResource(R.drawable.pre_btn_jnyj);
            auth.setText("缴纳押金");
        } else {
            authiv.setImageResource(R.drawable.ico_yirenz);
            auth.setText("已认证");
        }
        Cache.getUser().getData().setMoney(msg.getData().getMoney());
        Cache.getUser().getData().setUser_status(msg.getData().getUser_status());
    }

    void initSign() {
        if (msg.getData().getIs_sign() == 1) {
            sign.setText("已签到");
        }
    }

    @Override
    public void onSignSuccess(SignBean per) {
        if (msg.getData().getIs_sign() == 0) {
            ToastUtil.showSign(mContext, "+" + per.getData().getDoudou());
            msg.getData().setIs_sign(1);
            initSign();
        } else {
            ToastUtil.show(mContext, per.msg);
        }
    }

    String url = "";

    @Override
    public void setHeadImage(Bitmap bmp, String url) {
        Log.e(TAG, "url=" + url);
        this.url = url;
        myHandler = new MyHandler();
        MyThread m = new MyThread(url);
        new Thread(m).start();
    }

    @Override
    public void onError() {

    }

    @Override
    public void onHeadSuccess(String msg) {
        ToastUtil.show(mContext, msg);
        GlideUtil.setImage(mContext, url, R.drawable.head_img, R.drawable.head_img, userPic);
    }


    public class PersonalCenterAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public PersonalCenterAdapter() {
            super(R.layout.view_personal, Arrays.asList(itemList));
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.tv_name, item);
            helper.setImageResource(R.id.iv_pic, pic[helper.getLayoutPosition()]);
            if (helper.getPosition() < item.length() + 3)
                helper.getView(R.id.v_line).setVisibility(View.VISIBLE);
            else
                helper.getView(R.id.v_line).setVisibility(View.GONE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        personalCenterModel.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 权限选择后
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        personalCenterModel.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @OnClick({R.id.rel_home, R.id.title_share, R.id.ll_wallet, R.id.ll_sign, R.id.iv_auth, R.id.ll_shop, R.id.tv_me_head})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rel_home:
                Bundle b = new Bundle();
                b.putString(Cache.USER_ID, "");
                b.putString("phone", "");
                startActivity(PersonalHomePageActivity.class, b);
                break;
            case R.id.title_share:
                startActivity(SettingActivity.class);
                break;
            case R.id.ll_wallet:
                startActivity(MyWalletActivity.class);
                break;
            case R.id.ll_sign:
                personalCenterPresenter.initSign();
                break;
            case R.id.tv_me_head:
                AlertUtils.initPhotoAlertDialog(this, onPhotoType);
                break;
            case R.id.ll_shop:
                ToastUtil.show(mContext, "此功能在努力开发中");
                break;
            case R.id.iv_auth:
                if (Cache.getUser().getData().getMoney().equals("0")) {
                    startActivity(RealNameAuthenticationActivity.class);
                }
                break;
        }
    }

    /**
     * 选择图片弹窗监听
     */
    public CallBackColonyContract.OnPhotoType onPhotoType = new CallBackColonyContract.OnPhotoType() {

        @Override
        public void photoAlbum() {
            personalCenterModel.getFileByPhotoAlbum(PersonalCenterActivity.this);
            personalCenterModel.compressSize(mWidth, mHeight);
        }

        @Override
        public void photograph() {
            personalCenterModel.getFileByPhotograph(PersonalCenterActivity.this);
            personalCenterModel.compressSize(mWidth, mHeight);
        }
    };

    /**
     * 接受消息，处理消息 ，此Handler会与当前主线程一块运行
     */

    class MyHandler extends Handler {
        public MyHandler() {
        }

        public MyHandler(Looper L) {
            super(L);
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            // 此处可以更新UI
            Bundle b = msg.getData();
            String img64 = b.getString("img64");
            personalCenterPresenter.updataHead(img64);
        }
    }

    class MyThread implements Runnable {
        String path;

        MyThread(String path) {
            this.path = path;
        }

        public void run() {
            String img64 = FileUtil.bitmapToString(path);
            Message msg = new Message();
            Bundle b = new Bundle();// 存放数据
            b.putString("img64", img64);
            msg.setData(b);
            PersonalCenterActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息，更新UI

        }
    }
}
